package com.randev.snapservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.randev.snapconfig.Config;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;



public class LoginService extends IntentService{

	String userName = "";
	String password = "";
	Intent loginActivity = null;
	JSONObject responseObject = new JSONObject();
	int RESULT = 0;
	private final String TAG = "LoginService";
	
	public LoginService() {
		super("LoginService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Bundle extras = intent.getExtras();
		Log.i("LoginService Started", getClass().getSimpleName() + "");
		if (extras != null) {
			Messenger progressMessenger = (Messenger) extras.get("PROGRESS");
			Message progressMessage = Message.obtain();
			progressMessage.arg1 = 1;
			try {
				progressMessenger.send(progressMessage);
			} catch (android.os.RemoteException e1) {
				Log.w(TAG, "Exception sending progress message", e1);
			}
			
		}
		getDataFromPreviousActivity(intent);
		responseObject = validateUserNameAndPassword(userName, password);
		
		
		String status = "0";
		if (responseObject.length() == 0) {
			RESULT = -1;
			status = "0";
		} else {
			RESULT = 1;
			try {
				status = responseObject.getString("stauts");
			} catch (JSONException e) {
				Log.w("error getting status from object", e.toString());
				RESULT = -1;
				status = "0";
			}
		}
		
		String response = "";
		try {
			response = responseObject.getString("key");
		} catch (JSONException e) {
			Log.w("error getting key from object", e.toString());
			RESULT = -1;
			status = "0";
		}
		
		if (extras != null) {
			Messenger messenger = (Messenger) extras.get("MESSENGER");
			Message msg = Message.obtain();
			Bundle resultBundle = new Bundle();
			resultBundle.putString("Result", String.valueOf(RESULT));
			resultBundle.putString("Key", response);
			resultBundle.putString("Status", status);
			msg.setData(resultBundle);
			try {
				messenger.send(msg);
			} catch (android.os.RemoteException e1) {
				Log.w(TAG, "Exception sending message", e1);
			}
		}
		
		if (extras != null) {
			Messenger progressMessenger = (Messenger) extras.get("PROGRESS");
			Message progressMessage = Message.obtain();
			progressMessage.arg1 = 2;
			try {
				progressMessenger.send(progressMessage);
			} catch (android.os.RemoteException e1) {
				Log.w(TAG, "Exception sending progress message", e1);
			}
			
		}
		
		
		
	}

	private void getDataFromPreviousActivity(Intent intent) {
		Bundle dataFromPreviousActivity = new Bundle();
		dataFromPreviousActivity = intent.getExtras();
		try {
			userName = dataFromPreviousActivity.getString("UserName");
			password = dataFromPreviousActivity.getString("Password");
		} catch (Exception e) {
			Log.w(TAG, "Unable to get data from previous activity: " + e.toString());
		}
		
	}
	
	private JSONObject validateUserNameAndPassword(String userName, String password) {
		HttpClient httpClient = new DefaultHttpClient();
		String loginPostUrl = Config.LOGIN_POST;
		
		HttpPost loginPost = new HttpPost(loginPostUrl);
		loginPost.setHeader("Content-type", "application/x-www-form-urlencoded");
		
		ArrayList<NameValuePair> loginParameters = new ArrayList<NameValuePair>(2);
		StringBuilder stringBuilder = new StringBuilder();
		
		String responseString = "";
		JSONObject obj = new JSONObject();		
		loginParameters.add(new BasicNameValuePair("UserName", userName));  
		loginParameters.add(new BasicNameValuePair("Password", password));  
		
		try {
			loginPost.setEntity(new UrlEncodedFormEntity(loginParameters));
			HttpResponse response = httpClient.execute(loginPost);
			
			StatusLine statusLine = response.getStatusLine();
			int resultCode = statusLine.getStatusCode();
		    
		    if (resultCode == 200) {
		    	HttpEntity entity = response.getEntity();
		        InputStream content = entity.getContent();
		       
		        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		        String line = "";
		        while ((line = reader.readLine()) != null) {
		        	stringBuilder.append(line);
		        }
		        
		        obj = new JSONObject(stringBuilder.toString()); 
		    } else {
		    	Log.w("result code is not 200", resultCode + "");
		    	
		    }
		} catch (ClientProtocolException e) {
			Log.w(TAG, "Error Posting loging post"+ e.toString());
		} catch (IOException e) {
			Log.w(TAG, "Error Posting loging post"+ e.toString());
		} catch (JSONException e) {
			Log.w(TAG, "Error Posting loging post"+ e.toString());
		}
		
		responseString = stringBuilder.toString();
		Log.i(TAG, "Response from server:" + responseString + "");
		
		return obj;
	}
}
